package com.qqt.csr.im.assembler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.qqt.csr.im.dto.MsgAccountDTO;
import com.qqt.csr.im.dto.SendSystemMessageDTO;
import com.qqt.csr.im.entity.Account;
import com.qqt.csr.im.entity.msg.Message;
import com.qqt.csr.im.enums.MsgFlowTypeEnum;
import com.qqt.csr.im.enums.MsgTypeEnum;
import com.qqt.csr.im.enums.ReadFlagEnum;
import com.qqt.csr.im.entity.msg.TextContent;
import com.qqt.csr.common.utils.SnowflakeUtil;
import com.qqt.csr.im.vo.resp.MessageRespVO;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: yang hao
 * @Date: 2024/10/16 10:32
 * @Description: 消息装配器
 **/
public class MessageAssembler {

    /**
     * 转换
     * @param message {@link Message} 消息
     * @return {@link MessageRespVO} 离线消息视图
     */
    public static MessageRespVO convert(Message message) {
        return BeanUtil.copyProperties(message, MessageRespVO.class);
    }

    /**
     * 转换
     * @param messages {@link List <Message>} 消息
     * @return {@link List< MessageRespVO >} 离线消息视图
     */
    public static List<MessageRespVO> convert(List<Message> messages) {
        if (CollectionUtils.isEmpty(messages)) {
            return Lists.newArrayList();
        }
        return messages.stream()
                .map(MessageAssembler::convert)
                .collect(Collectors.toList());
    }

    /**
     * 转换
     * @param dto {@link SendSystemMessageDTO} 系统消息
     * @param account {@link Account} 账户消息
     * @return {@link Message} 消息
     */
    public static Message convert(SendSystemMessageDTO dto, Account account) {
        String date = DateUtil.now();
        return Message.builder()
                .seq(SnowflakeUtil.nextIdStr())
                .recipient(MsgAccountDTO.builder().id(account.getId().toString()).build())
                .conversationId(dto.getConversationId())
                .content(TextContent.of(dto.getMessage()))
                .flow(MsgFlowTypeEnum.IN)
                .artificialExt(dto.getExt())
                .type(MsgTypeEnum.SystemElem)
                .readFlag(dto.getReadFlag() != null ? dto.getReadFlag() : ReadFlagEnum.UNREAD)
                .roomId(dto.getRoomId())
                .createTime(date)
                .updateTime(date)
                .build();
    }
}
